<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

use Ptime3\Functions\JoinData;
use Ptime3\Functions\Queue;

class StarController extends Controller
{
     /**
     * @api {get} /star GetStarList
     * @apiVersion 0.2.0
     * @apiName GetStarList
     * @apiGroup comment
     * @apiPermission app
     *
     * @apiDescription 获取赞列表
     *
     * @apiParam {Number} app_id *应用id.
     * @apiParam {String} object *实体名称.
     * @apiParam {Number} object_id *实体id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object[]} result 数据.
     * @apiSuccess {Datetime} result.created_at 创建时间.
     * @apiSuccess {String} result.user_name 用户姓名.
     * @apiSuccess {String} result.user_icon 用户头像.
     * @apiSuccess {String} message 提示消息
     *
     * @apiError statusError 状态错误.
     * @apiSampleRequest http://dev.timepicker.cn/api/star
     */
    function index(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'app_id'      => 'required|integer|min:1',
                'object'      => 'required|string|min:2',
                'object_id'   => 'required|integer|min:1'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $appId      = $input["app_id"];
        $object     = $input["object"];
        $objectId   = $input["object_id"];

        $starResult = DB::table("cm_star")
          ->select("created_at","user_id")
          ->where("app_id",$appId)
          ->where("object",$object)
          ->where("object_id",$objectId)
          ->orderBy("created_at","DESC")
          ->get();

        $starResult = JoinData::user($starResult);

        return $this::jsonResponse(false,$starResult);
    }

    /**
     * @api {post} /star CreateStar
     * @apiVersion 0.2.0
     * @apiName CreateStar
     * @apiGroup comment
     * @apiPermission app
     *
     * @apiDescription 创建赞
     *
     * @apiParam {Number} app_id *应用id.
     * @apiParam {String} object *实体名称.
     * @apiParam {Number} object_id *实体id.
     * @apiParam {Number} user_id *用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Number} result 新建赞id.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.120:82/api/star
     */
     public function store(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'app_id'      => 'required|integer|min:1',
                'object'      => 'required|string|min:2',
                'object_id'   => 'required|integer|min:1',
                'user_id'     => 'required|integer|min:1',
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $appId      = $input["app_id"];
        $object     = $input["object"];
        $objectId   = $input["object_id"];
        $userId     = $input["user_id"];

        $starResult = DB::table("cm_star")
            ->where("app_id",$appId)
            ->where("object",$object)
            ->where("object_id",$objectId)
            ->where("user_id",$userId)
            ->pluck("id");

        if(!empty($starResult))
            return $this::jsonResponse(true,"","star exist");

        
        $starData = [
            "app_id" => $input["app_id"],
            "object" => $input["object"],
            "object_id" => $input["object_id"],
            "user_id" => $input["user_id"]
        ];

        DB::beginTransaction();
        $starId = DB::table("cm_star")->insertGetId($starData);

        $incrementResult = DB::table("cm_object")
          ->where("app_id",$input["app_id"])
          ->where("object",$input["object"])
          ->where("object_id",$input["object_id"])
          ->increment("star_count");
        
        if(!$incrementResult){
          $objectData = [
            "app_id" => $input["app_id"],
            "object" => $input["object"],
            "object_id" => $input["object_id"],
            "star_count" => 1
          ];
          DB::table("cm_object")->insert($objectData);
        }
        DB::commit();

        $eventHookData = [
            "app_id"=>$input["app_id"],
            "event" =>"starStore",
            "data"  =>"{{user:id:$userId:name}}"
        ];
        Queue::put("appevent",$eventHookData);

        return $this->jsonResponse(false,$starId);
     }

    /**
     * @api {delete} /star DeleteStar
     * @apiVersion 0.2.0
     * @apiName DeleteStar
     * @apiGroup comment
     * @apiPermission app
     *
     * @apiDescription 删除赞
     *
     * @apiParam {Number} app_id *应用id.
     * @apiParam {String} object *实体名称.
     * @apiParam {Number} object_id *实体id.
     * @apiParam {Number} user_id *用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Boolean} result 结果.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.120:82/api/star
     */
     public function destroy(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'app_id'      => 'required|integer|min:1',
                'object'      => 'required|string|min:2',
                'object_id'   => 'required|integer|min:1',
                'user_id'     => 'required|integer|min:1',
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $appId      = $input["app_id"];
        $object     = $input["object"];
        $objectId   = $input["object_id"];
        $userId     = $input["user_id"];

        $starId = DB::table("cm_star")
            ->where("app_id",$appId)
            ->where("object",$object)
            ->where("object_id",$objectId)
            ->where("user_id",$userId)
            ->value("id");

        if(empty($starId))
            return $this::jsonResponse(true,"","star not exist");

        DB::beginTransaction();
        DB::table("cm_star")
            ->where("id",$starId)
            ->delete();
        
        DB::table("cm_object")
           ->where("app_id",$appId)
           ->where("object",$object)
           ->where("object_id",$userId)
           ->decrement("star_count");
        DB::commit();

        return $this->jsonResponse(false,true);
     }

}